﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Business;
using Core.Entity;
using System.Globalization;
namespace TicketManagement.Staff
{
    public partial class Profile : System.Web.UI.Page
    {
        private int id = 0;
        private StaffBus bus = new StaffBus();
        private UserBus userBus = new UserBus();
        private Core.Entity.Staff staff;
        private Core.Entity.User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.authenticate();

            try
            {
                id = int.Parse(Session["User"].ToString());
                staff = bus.getStaffByUserId(id);
                user = userBus.get(staff.UserId);
            }
            catch (Exception ex) { }

            if (!IsPostBack)
            {
                this.loadUserType();
                cboUserType.Enabled = false;
                this.loadData();
            }
        }

        private void authenticate()
        {
            if (Session["User"] != null)
            {
                Core.Entity.User curUser = userBus.get(Convert.ToInt32(Session["User"]));
                if (curUser.UserTypeId == 4)
                {
                    // Do not allow customer here
                    Response.Redirect("/Home/Index.aspx", true);
                }
            }
        }

        public void loadUserType()
        {
            UserTypeBus userTypeBus = new UserTypeBus();
            List<UserType> userTypes = new List<UserType>();
            userTypes = userTypeBus.getAll();
            cboUserType.DataSource = userTypes;
            cboUserType.DataBind();
        }

        public void loadData()
        {
            if (id != 0)
            {
                txtUsername.Value = user.Username;
                txtCode.Value = staff.Code;
                txtEmail.Value = user.Email;
                rbtActive.Checked = user.IsActive;
                rbtNotActive.Checked = !user.IsActive;
                cboUserType.SelectedIndex = user.UserTypeId;
                txtRealName.Value = staff.FullName;
                cboGender.SelectedIndex = (staff.Gender == true) ? 0 : 1;
                txtBirthday.Value = staff.BirthDay.ToString("dd/MM/yyyy");
                txtHireDate.Value = staff.HireDate.ToString("dd/MM/yyyy");
                txtPhoneNumber.Value = staff.Phone;
                txtAddress.Value = staff.Address;
                txtDesc.Value = staff.Desc;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (validate())
            {
                this.updateData();
            }
        }

        private void updateData()
        {
            // User
            user.Username = txtUsername.Value.Trim();
            if (txtPassword.Value != "")
            {
                user.Password = txtNewPassword.Value.Trim();
            }
            user.Email = txtEmail.Value;
            user.IsActive = rbtActive.Checked;
            user.UserTypeId = int.Parse(cboUserType.SelectedValue);
            
            // Staff
            staff.Code = txtCode.Value.Trim();
            staff.FullName = txtRealName.Value.Trim();
            staff.Gender = (cboGender.Value == "1") ? true : false;

            try
            {
                DateTime birthday = DateTime.ParseExact(txtBirthday.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                staff.BirthDay = birthday;
            }
            catch (Exception ex) { }

            try
            {
                DateTime hireDate = DateTime.ParseExact(txtHireDate.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                staff.HireDate = hireDate;
            }
            catch (Exception ex) { }

            staff.Phone = txtPhoneNumber.Value.Trim();
            staff.Address = txtAddress.Value.Trim();
            staff.Desc = txtDesc.Value.Trim();

            if (userBus.update(user) && bus.update(staff))
            {
                String script = "alert('Cập nhật thành công!'); location.href='/Staff/Index.aspx';";
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", script, true);
            }
            else
            {
                lblMessage.InnerText = "Không cập nhật được. Vui lòng kiểm tra lại dữ liệu nhập vào";
            }
        }

        public bool validate()
        {
            //bool isValid = true;

            if (staff.Id > 0)
            {
                // Edit
                if (txtPassword.Value != "")
                {
                    if (txtPassword.Value != user.Password)
                    {
                        correctPasswordValidator.IsValid = false;
                        return false;
                    }

                    if (txtNewPassword.Value == "")
                    {
                        requireNewPassword.IsValid = false;
                        return false;
                    }
                }
            }

            if (txtUsername.Value != user.Username)
            {

                if (userBus.isUsernameExist(txtUsername.Value))
                {
                    exitsUsername.IsValid = false;
                    return false;
                }
            }

            if (txtEmail.Value != user.Email)
            {
                if (userBus.isEmailExist(txtEmail.Value))
                {
                    exitsEmail.IsValid = false;
                    return false;
                }
            }

            return true;
        }
    }
}